package com.xyh.reward_kotlin.adapter

import android.content.Context
import android.content.Intent
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.PopupMenu
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.xyh.reward_kotlin.R
import com.xyh.reward_kotlin.activity.HistoryDetailActivity
import com.xyh.reward_kotlin.api.ApiCallback
import com.xyh.reward_kotlin.api.ApiClient
import com.xyh.reward_kotlin.api.RewardApi
import com.xyh.reward_kotlin.response.ResultDto
import com.xyh.reward_kotlin.response.RewardResultDto
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class HistoryAdapter(
    private val context: Context,
    var historyList: MutableList<RewardResultDto>
) : RecyclerView.Adapter<HistoryAdapter.ViewHolder>() {

    var onDeleteClick: ((RewardResultDto) -> Unit)? = null
    var onExportClick: ((RewardResultDto) -> Unit)? = null
    var onPinClick: ((RewardResultDto) -> Unit)? = null

    private val rewardApi: RewardApi = ApiClient.client.create(RewardApi::class.java)

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var titleText: TextView = itemView.findViewById(R.id.historyTitleText)
        var timeText: TextView = itemView.findViewById(R.id.historyTimeText)
        var btnMore: ImageView = itemView.findViewById(R.id.btnMore)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view: View = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_history, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item: RewardResultDto = historyList[position]
        val timestamp = formatTimestamp(item.timestamp)
        val title = "总奖励：" + item.totalReward
        holder.titleText.text = title
        holder.timeText.text = timestamp

        // 点击进入详情
        holder.itemView.setOnClickListener {
            val intent = Intent(context, HistoryDetailActivity::class.java)
            intent.putExtra("rewardItem", item)
            context.startActivity(intent)
        }

        // 更多操作菜单
        holder.btnMore.setOnClickListener { v ->
            val popup = PopupMenu(context, v, Gravity.END, 0, R.style.CompactPopupMenu)
            popup.menuInflater.inflate(R.menu.history_item_menu, popup.menu)
            popup.setOnMenuItemClickListener { menuItem ->
                when (menuItem.itemId) {
                    R.id.action_delete -> { onDeleteClick?.invoke(item); true }
                    R.id.action_export -> { onExportClick?.invoke(item); true }
                    else -> false
                }
            }
            popup.show()
        }
    }

    override fun getItemCount(): Int = historyList.size

    private fun formatTimestamp(timestamp: Long): String {
        val date = Date(timestamp)
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
        return sdf.format(date)
    }

    fun updateData(newList: List<RewardResultDto>) {
        historyList = newList.toMutableList()
        notifyDataSetChanged()
    }

    // 提供删除和置顶的工具方法
    fun removeItem(item: RewardResultDto) {
        val pos = historyList.indexOf(item)
        if (pos != -1) {
            historyList.removeAt(pos)
            notifyItemRemoved(pos)
            rewardApi.deleteReward(item.id).enqueue(object : ApiCallback<ResultDto<Void>>() {
                override fun onSuccess(result: ResultDto<Void>) {
                    Log.d("history", "删除成功")
                }

                override fun onError(errorMsg: String?) {
                    Log.e("history", "删除失败$errorMsg")
                }
            })
        }
    }

    fun pinItem(item: RewardResultDto) {
        val pos = historyList.indexOf(item)
        if (pos != -1) {
            historyList.removeAt(pos)
            historyList.add(0, item)
            notifyItemMoved(pos, 0)
        }
    }
}
